import { Form, Input, Modal, Cascader } from 'antd';
import { useEffect, useState } from 'react';

export function AddressModal({ title, show, formValue, onOk, onCancel, tree }: any) {
  const [form] = Form.useForm();
  const [ids, setIds] = useState<any>([]);
  const [text, setText] = useState<string>('');
  useEffect(() => {
    const ssq =
      formValue.proId && formValue.cityId && formValue.disId
        ? [formValue.proId, formValue.cityId, formValue.disId]
        : null;
    form.setFieldsValue({ ...formValue, ssq });
    setIds(ssq);
    setText(formValue.pcdText);
  }, [formValue, form]);

  const handleAddress = (e: any, v: any) => {
    setIds([e[0], e[1], e[2]]);
    setText(`${v[0].name} ${v[1].name} ${v[2].name}`);
  };

  const handleSubmit = () => {
    form.validateFields().then((fieldsValue) => {
      onOk({
        ...formValue,
        ...fieldsValue,
        proId: ids[0],
        cityId: ids[1],
        disId: ids[2],
        pcdText: text,
      });
    });
  };
  return (
    <Modal title={title} open={show} onCancel={onCancel} onOk={() => handleSubmit()} centered>
      <Form
        initialValues={formValue}
        form={form}
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 18 }}
        layout="horizontal"
      >
        <Form.Item<any>
          label="联系人"
          name="contactName"
          rules={[{ required: true, whitespace: true, message: '联系人不能为空' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item<any>
          label="手机号"
          name="mobile"
          rules={[
            { required: true, whitespace: true, message: '手机号不能为空' },
            { pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/, message: '请输入正确的手机号' },
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item<any>
          label="邮编"
          name="zip"
          rules={[{ required: true, whitespace: true, message: '邮编不能为空' }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="省市区"
          name="ssq"
          rules={[{ required: true, message: '省市区不能为空' }]}
        >
          <Cascader
            value={ids}
            onChange={(e, v) => handleAddress(e, v)}
            options={tree}
            fieldNames={{ label: 'name', value: 'id', children: 'sonList' }}
          />
        </Form.Item>
        <Form.Item<any>
          label="详细地址"
          name="address"
          rules={[{ required: true, whitespace: true, message: '详细地址不能为空' }]}
        >
          <Input />
        </Form.Item>
      </Form>
    </Modal>
  );
}
